const {MongoClient} = require('mongodb');

const sqlUrl = "mongodb://localhost:27017/htt_MongoDB";
const dbName = 'better_me';
const client = new MongoClient(sqlUrl);

client.connect((err) => {
    if (err) {
        console.log('数据库连接错误');
        client.close();
        return;
    }
});
//切换到要操作的数据库
let db = client.db(dbName);
console.log('数据库连接成功ByHTT');

function querySql(table, sql) {
    return new Promise((resolve, reject) => {
        let result = "";
        db.collection(table).find(sql).toArray((err, data) => {
            if (err) {
                reject("查询失败");
            }
            result = JSON.stringify(data);
            resolve(result);
            // client.close();
        });
    });
}

function updateSql(table, where, sql) {
    return new Promise((resolve, reject) => {
        db.collection(table).updateOne(where, sql, (err, data) => {
            if (err) {
                reject("更新失败");
            }
            resolve("更新成功");
            // client.close();
        })
    });
}

function insertSql(table, sql) {
    return new Promise((resolve, reject) => {
        db.collection(table).insertOne(sql, (err, data) => {
            if (err) {
                reject("添加失败");
            }
            resolve("添加成功");
            // client.close();
        })
    });
}

function deleteSql(table, sql) {
    return new Promise((resolve, reject) => {
        db.collection(table).deleteOne(sql, (err, result) => {
            if (err) {
                reject("删除失败");
            }
            resolve("删除成功");
            // client.close();
        })
    });
}

function squareSql(req, res, collection){
    db.collection(collection).find(queryRequest(req)).skip(req.start).limit(req.num).toArray(function (err, result) {
        if (err) throw err;
        res.setHeader("Access-Control-Allow-Origin", "*");      //允许跨域
        res.writeHead(200, {'Content-Type': 'text/html; charset = UTF-8'});
        res.end(JSON.stringify({result}));
        // db.close();
    });
}

function queryRequest(req) {
    return req.email ? req.id ? {'email': req.email, 'id': req.id} : {'email': req.email} : '';
}

module.exports = {querySql, updateSql, insertSql, deleteSql,squareSql};
